import axios from 'axios';
import Cookie from 'js-cookie';

// 跨域认证信息 header 名
const xsrfHeaderName = 'Authorization';

axios.defaults.timeout = 15000;
// axios.defaults.withCredentials = true
// axios.defaults.xsrfHeaderName = xsrfHeaderName
// axios.defaults.xsrfCookieName = xsrfHeaderName

// 认证类型
const AUTH_TYPE = {
  BEARER: 'Bearer',
  BASIC: 'basic',
  AUTH1: 'auth1',
  AUTH2: 'auth2',
};

// http method
const METHOD = {
  GET: 'get',
  POST: 'post',
  DELETE: 'delete',
  PUT: 'put',
};

/**
 * axios请求
 * @param url 请求地址
 * @param method {METHOD} http method
 * @param params 请求参数
 * @returns {Promise<AxiosResponse<T>>}
 */
async function request(url, method, params, config) {
  console.log(params);
  switch (method) {
    case METHOD.GET:
      return axios.get(url, { params, ...config });
    case METHOD.POST:
      return axios.post(url, params, config);
    case METHOD.DELETE:
      return axios.delete(url + params, params);
    case METHOD.PUT:
      return axios.put(url + params.id, params);
    case METHOD.DYNAMIC:
      return axios.get(url + params, config);
    case METHOD.UPDATE:
      return axios.update(url + params.id, params);
    default:
      return axios.get(url, { params, ...config });
  }
}

/**
 * 设置认证信息
 * @param auth {Object}
 * @param authType {AUTH_TYPE} 认证类型，默认：{AUTH_TYPE.BEARER}
 */
function setAuthorization(auth, authType = AUTH_TYPE.BEARER) {
  switch (authType) {
    case AUTH_TYPE.BEARER:
      Cookie.set(xsrfHeaderName, auth.token, { expires: auth.expireAt });
      break;
    case AUTH_TYPE.BASIC:
    case AUTH_TYPE.AUTH1:
    case AUTH_TYPE.AUTH2:
    default:
      break;
  }
}

/**
 * 移出认证信息
 * @param authType {AUTH_TYPE} 认证类型
 */
function removeAuthorization(authType = AUTH_TYPE.BEARER) {
  switch (authType) {
    case AUTH_TYPE.BEARER:
      Cookie.remove(xsrfHeaderName);
      break;
    case AUTH_TYPE.BASIC:
    case AUTH_TYPE.AUTH1:
    case AUTH_TYPE.AUTH2:
    default:
      break;
  }
}

/**
 * 检查认证信息
 * @param authType
 * @returns {boolean}
 */
function checkAuthorization(authType = AUTH_TYPE.BEARER) {
  switch (authType) {
    case AUTH_TYPE.BEARER:
      if (Cookie.get(xsrfHeaderName)) {
        return true;
      }
      break;
    case AUTH_TYPE.BASIC:
    case AUTH_TYPE.AUTH1:
    case AUTH_TYPE.AUTH2:
    default:
      break;
  }
  return false;
}

/**
 * 加载 axios 拦截器
 * @param interceptors
 * @param options
 */
function loadInterceptors(interceptors, options) {
  //axios 请求拦截
  axios.interceptors.request.use((config) => {
    let token = Cookie.get(xsrfHeaderName) || '';
    if (token) {
      //给请求头添加token
      if (localStorage.getItem('e-token')) {
        //超管获取其他用户信息或操作添加e-token
        config.headers['e-token'] = localStorage.getItem('e-token');
      }
      config.headers['authorization'] = token;
      config.headers['Content-type'] = 'application/json';
    }
    return { ...config };
  });
  //axios 返回拦截
  axios.interceptors.response.use(
    (response) => {
      return response.data;
    },
    (error) => {
      (function(resp) {
        console.group(
          `%c【代码${resp.status}: ${resp.data.msg}】`,
          'color:blue;font-size:15px;'
        );
        let inputdata = resp.config.data
          ? JSON.parse(resp.config.data)
          : undefined;
        let inputparams = resp.config.params ? resp.config.params : undefined;

        console.groupEnd();
      })(error.response);
      if (error.response.status === 401 || error.response.status === 403) {
        const { router } = options;
        router.push('/login');
      }
      return Promise.reject(error.response.data);
    }
  );
}

/**
 * 解析 url 中的参数
 * @param url
 * @returns {Object}
 */
function parseUrlParams(url) {
  const params = {};
  if (!url || url === '' || typeof url !== 'string') {
    return params;
  }
  const paramsStr = url.split('?')[1];
  if (!paramsStr) {
    return params;
  }
  const paramsArr = paramsStr.replace(/&|=/g, ' ').split(' ');
  for (let i = 0; i < paramsArr.length / 2; i++) {
    const value = paramsArr[i * 2 + 1];
    params[paramsArr[i * 2]] =
      value === 'true' ? true : value === 'false' ? false : value;
  }
  return params;
}

export {
  METHOD,
  AUTH_TYPE,
  request,
  setAuthorization,
  removeAuthorization,
  checkAuthorization,
  loadInterceptors,
  parseUrlParams,
  axios,
};
